import React, {forwardRef, useEffect, useImperativeHandle, useState} from "react";
import { Button, Modal, Space, Table, TableColumnType, message, Form, Input } from "antd";
import { clueCompanyTypes, companyTypes  } from "@/constants/types";
import { fetchClueList, receiveClueCompany, addCompany, addClueCustomerTag } from "../services";
import { calculateTableWidth } from "@/utils/util";
import CompanyUpdate from "../modals/CompanyUpdate";
import { useRequest } from "ahooks";
import XlTableDictColumn from "@/components/Table/XlTableDictColumn";
import { isClueStatusDone } from "@/utils/dictUtil";
import CluRemark from "../modals/CluRemark";
import { useComponentDidMount } from "@/hooks";
import ClueCall from "../modals/ClueCall";


interface tabProps {
  activeKey: string;
  tabKey: string,
  refreshNum: Function,
  tabChangeShouldUpdateTab: string[]
}

const {Item} = Form;

const CluePoolTable = forwardRef(({activeKey, tabKey, refreshNum, tabChangeShouldUpdateTab}: tabProps, ref) => {
  const [dataSource, setDataSource] = useState([]);
  const [pagination, setPagination] = useState({
    pageNum: 1,
    pageSize: 10,
    total: 0
  });

  // 转客户
  const [currentRow, setCurrentRow] = useState<clueCompanyTypes | null>(null);
  const [certifyVisible, setCertifyVisible] = useState<boolean>(false);
  const {loading: certifyLoading, runAsync: certifyCompanyApi} = useRequest(addCompany, {manual: true});
  // 备注
  const [remarkVisible, setRemarkVisible] = useState<boolean>(false);
  const {loading: remarkLoading, runAsync: addClueCustomerTagApi} = useRequest(addClueCustomerTag, {manual: true});
  // 拨号 
  const [calleds, setCalleds] = useState<string []>([]);
  const [calling, setCalling] = useState<string>('');
  const [callVisible, setCallVisible] = useState<boolean>(false);

  const isAll = activeKey === "all";

  const [form] = Form.useForm();

  const search = async (params: any) => {
    const statusMaps: any = {
      waitClaimNum: '0',
      claimedNum: '1'
    }
    const res = await fetchClueList({
      ...params,
      status: statusMaps?.[tabKey]
    });
    setDataSource(res?.data || []);
    setCalleds([]);
    setCalling('');
    setPagination({
      ...params,
      total: res?.total
    });
  }

  // 刷新table
  const refreshTable = () => {
    if (activeKey !== tabKey) {
      return ;
    }
    search({
      pageNum: 1,
      pageSize: 10,
      ...(isAll ? form.getFieldsValue() : {})
    });
  }

  // 移除已领取
  const removeRow = (record: clueCompanyTypes) => {
    const arr = [...dataSource];
    const index = arr?.findIndex((v: clueCompanyTypes) => v?.id === record?.id);
    arr.splice(index, 1);
    setDataSource(arr);
  }

  // 客户认证
  const certifyProps = {
    visible: certifyVisible,
    clueRow: currentRow,
    title: '线索转客户',
    loading: certifyLoading,
    onCancel: () => {
      setCurrentRow(null);
      setCertifyVisible(false);
    },
    onSubmit: async (params: companyTypes) => {
      const res = await certifyCompanyApi(params);
      if (res?.code === '0') {
        message.success('转客户成功!');
        certifyProps.onCancel();
        refreshTable();
      }
    }
  }
  // 添加备注
  const remarkProps = {
    visible: remarkVisible,
    title: '添加备注',
    currentRow,
    loading: remarkLoading,
    onCancel: () => {
      setCurrentRow(null);
      setRemarkVisible(false);
    },
    onSubmit: async (params: any) => {
      const res = await addClueCustomerTagApi(params);
      if (res?.code === '0') {
        message.success('添加成功!');
        remarkProps.onCancel();
      } else {
        message.warning('添加失败');
      }
    }
  }
  // 拨打电话
  const clueCallProps = {
    visible: callVisible,
    title: '拨打电话',
    dataSource,
    currentRow: calling,
    onCancel: () => {
      setCalling("");
      setCallVisible(false);
    },
    onSubmit: (record: clueCompanyTypes) => {
      setCalleds([...calleds, record?.id]);
    }
  }
  


  const handleCertify = (record: clueCompanyTypes) => {
    setCurrentRow(record);
    setCertifyVisible(true);
  }
  // 认领客户
  const handleReceive = (record: clueCompanyTypes) => {
    Modal.confirm({
      title: '温馨提示',
      content: '确定要认领此客户吗？',
      onOk: () => {
        receiveClueCompany({id: record?.id}).then(
          res => {
            if (res?.code === '0') {
              message.success('认领成功!');
              removeRow(record);
              refreshNum();
            }
          }
        )
      }
    });
  }
  const handleRemark = (record: clueCompanyTypes) => {
    setCurrentRow(record);
    setRemarkVisible(true);
  }


  const fieldColumns: TableColumnType<clueCompanyTypes> [] = [
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (_, record) => <XlTableDictColumn type="clueStatus" value={record?.status} />
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      width: 120
    },
    {
      title: '呢称/姓名',
      dataIndex: 'nickName',
      ellipsis: true,
      width: 150
    },
    {
      title: '公司名称',
      dataIndex: 'fullName',
      ellipsis: true,
      width: 180
    },
    {
      title: '地址',
      dataIndex: 'address',
      ellipsis: true,
      width: 150
    },
    {
      title: '入公海时间',
      dataIndex: 'createTime',
      width: 150
    },
    {
      title: '来源类型',
      dataIndex: 'channel',
      width: 120
    },
    {
      title: '具体渠道来源',
      dataIndex: 'source',
      ellipsis: true,
      width: 150
    },
    {
      title: '操作',
      dataIndex: 'options',
      width: 150,
      fixed: 'right',
      render: (_, record) => {
        if (isClueStatusDone(record?.status)) {
         return (
          <Space>
            <Button onClick={(e) => {
              e.stopPropagation();
              handleCertify(record)
            }} type="link">转客户</Button>
            {/* <Button onClick={() => handleRemark(record)} type="link">备注</Button> */}
          </Space>
         )
        }
        return (
          <Space>
            <Button onClick={(e) => {
              e.stopPropagation();
              handleReceive(record)
            }} type="link">认领</Button>
            <Button onClick={(e) => {
              e.stopPropagation();
              handleRemark(record)
            }} type="link">备注</Button>
          </Space>
        );
      }
    },
  ];
 

  const getColumns = () => {
    return fieldColumns;
  }

  const handleSearch = () => {
    const params = form.getFieldsValue();
    search({
      ...params,
      pageNum: 1,
      pageSize: 10,
    });
  }
  const handleReset = () => {
    form.resetFields();
    search({
      pageNum: 1,
      pageSize: 10,
    });
  }


  useImperativeHandle(ref, () => ({
    refreshTable,
    removeRow
  }));


  useEffect(() => {
    if (tabKey === activeKey && tabChangeShouldUpdateTab.includes(activeKey)) {
      search({
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize,
        ...(isAll ? form.getFieldsValue() : {})
      });
    }
  }, [tabKey, activeKey]);

  useComponentDidMount(() => {
    if (!tabChangeShouldUpdateTab.includes(activeKey)) {
      search({
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize,
        ...(isAll ? form.getFieldsValue() : {})
      });
    }
  })


  return (
    <>
      {
        activeKey === "all" && (
          <Form form={form} layout="inline" style={{marginBottom: 10}}>
            <Item label="手机号" name="mobile">
              <Input style={{width: 250}} />
            </Item>
            <Item>
              <Space>
                <Button type="primary" onClick={handleSearch}>查询</Button>
                <Button type="default" onClick={handleReset}>重置</Button>
              </Space>
            </Item>
          </Form>
        )
      }
      <Table
         bordered
         rowKey="id"
         dataSource={dataSource}
         columns={getColumns()}
         rowClassName={(record) => calleds?.includes(record?.id) ? 'bg-called' : ''}
         scroll={{x: calculateTableWidth(getColumns())}}
         onRow={(record) => {
          return {
            onClick: () => {
              setCalling(record?.id);
              setCalleds([...calleds, record?.id]);
              setCallVisible(true);
            }, // 点击行
          };
        }}
         pagination= {tabChangeShouldUpdateTab?.includes(activeKey) ? {
          showTotal: (total: number) => `共 ${total} 条`,
          ...pagination,
          onChange: (pageNum, pageSize) => {
            search({pageNum, pageSize, ...(isAll ? form.getFieldsValue() : {})});
          }
         } : false}
      />
      {certifyVisible && <CompanyUpdate {...certifyProps} />} 
      {remarkVisible && <CluRemark {...remarkProps} />}
      {callVisible && <ClueCall {...clueCallProps} />}
    </>
  );
});


export default CluePoolTable;